package server;

import java.net.*;

public abstract class AbsServer {
	private boolean is_running = false;

	private DatagramSocket socket;
	private int port;
	private ServiceThread srvThread;

	public AbsServer(int port) {
		this.port = port;
	}

	public boolean isRunning() {
		return this.is_running;
	}

	public boolean start() {
		try {
			socket = new DatagramSocket(port);
			srvThread = new ServiceThread();
			srvThread.start();
			is_running = true;

			System.out.println("server start at: " + socket.getLocalAddress()
					+ " " + socket.getLocalPort());

			return true;
		} catch (SocketException e) {
			e.printStackTrace();
			return false;
		}
	}

	public void stop() {
		// srvThread.stop();
		socket.close();
		is_running = false;
	}

	abstract public void replyAction(DatagramSocket socket, DatagramPacket pkt)
			throws Exception;

	private class ServiceThread extends Thread {
		@Override
		public void run() {
			while (!socket.isClosed()) {
				byte buf[] = new byte[200];
				DatagramPacket pkt = new DatagramPacket(buf, buf.length);
				try {
					socket.receive(pkt);

					String s = new String(pkt.getData(), 0, pkt.getLength());
					pkt.setData(s.getBytes());

					replyAction(socket, pkt);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

}
